﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Sinacor.Infra.Core.Licensing;
using Sinacor.Infra.Core.Licensing.Business;
using System.Collections.Generic;
using WebLicenseGenerator.UC;

namespace WebLicenseGenerator
{
	public partial class SearchHistory : System.Web.UI.Page
	{
		Licensing _search;
		Licenca _licenseBusiness;
		Empresa _companyBusiness;
		Confirmation _confirmation;
		Sinacor.Infra.Core.Licensing.Business.Alias _aliasBusiness = null;
		List<Licensing> _licenseTable
		{
			get { return ViewState["LicenseTable"] as List<Licensing>; }
			set { ViewState["LicenseTable"] = value; }
		}
		Licensing _selectedLicense
		{
			get { return ViewState["SelectedLicense"] as Licensing; }
			set { ViewState["SelectedLicense"] = value; }
		}
		public static string scrollClientID = String.Empty;

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				cbHistoryType.Items.Add("");
				cbHistoryType.Items.Add(new ListItem(Sinacor.Infra.Core.Licensing.TypeDescription.Alterar.ToString(), ((int)Sinacor.Infra.Core.Licensing.TypeDescription.Alterar).ToString()));
				cbHistoryType.Items.Add(new ListItem(Sinacor.Infra.Core.Licensing.TypeDescription.Excluir.ToString(), ((int)Sinacor.Infra.Core.Licensing.TypeDescription.Excluir).ToString()));
				cbHistoryType.Items.Add(new ListItem(Sinacor.Infra.Core.Licensing.TypeDescription.Incluir.ToString(), ((int)Sinacor.Infra.Core.Licensing.TypeDescription.Incluir).ToString()));
				cbHistoryType.Items.Add(new ListItem(Sinacor.Infra.Core.Licensing.TypeDescription.Restaurar.ToString(), ((int)Sinacor.Infra.Core.Licensing.TypeDescription.Restaurar).ToString()));
				cbHistoryType.SelectedIndex = -1;

				this.LoadAliases();

				scrollClientID = ((HtmlInputHidden)scrollPos).ClientID.ToString();
			}

			_confirmation = ((WebLicenseGenerator.UC.Confirmation)this.Master.FindControl("confirmationPanel"));
			_confirmation.OnConfirmation += new Confirmation.ConfirmationEventHandler(OnConfirmation);
		}

		protected void btSearch_Click(object sender, EventArgs e)
		{
			if (this.ValidatePageFields())
			{
				List<Licensing> returnList;
				_search = new Sinacor.Infra.Core.Licensing.Licensing();
				_licenseBusiness = new Licenca();

				if (string.IsNullOrEmpty(txtLicenseId.Text.Trim()))
					_search.Id = null;
				else
					_search.Id = Convert.ToInt32(txtLicenseId.Text.Trim());

				if (cbAliases.SelectedIndex <= 0)
				    _search.AliasId = null;
				else
				    _search.AliasId = Convert.ToInt32(cbAliases.SelectedItem.Value);

				if (String.IsNullOrEmpty(dpHistoryDate.Text))
					_search.Description.Period = null;
				else
					_search.Description.Period = new DateTime(Int32.Parse(dpHistoryDate.Text.Substring(6, 4)), Int32.Parse(dpHistoryDate.Text.Substring(3, 2)), Int32.Parse(dpHistoryDate.Text.Substring(0, 2)));

				if (cbHistoryType.SelectedIndex <= 0)
					_search.Description.TypeDescription = null;
				else
				{
					switch (cbHistoryType.SelectedValue)
					{
						case "1":
							_search.Description.TypeDescription = TypeDescription.Incluir;
							break;
						case "2":
							_search.Description.TypeDescription = TypeDescription.Alterar;
							break;
						case "3":
							_search.Description.TypeDescription = TypeDescription.Excluir;
							break;
						case "4":
							_search.Description.TypeDescription = TypeDescription.Restaurar;
							break;
					}
				}

				returnList = _licenseBusiness.SelecionarHistorico(_search);

				if (returnList.Count == 0)
					this.ShowMessageDialog("Nenhum dado encontrado", "Não foram encontrados dados que satisfaçam a pesquisa.");

				gvHistory.DataSource = returnList;
				_licenseTable = returnList;
				gvHistory.DataBind();
			}
		}

		protected void rdRestoreCheckedChanged(object sender, EventArgs e)
		{
			if (sender is RadioButton)
			{
				foreach (GridViewRow r in gvHistory.Rows)
					((RadioButton)r.Cells[8].FindControl("rdRestore")).Checked = false;

				_selectedLicense = _licenseTable.Find(l => l.Id.Value == int.Parse(((RadioButton)sender).Attributes["LicenseId"]));

				this.ShowConfirmationDialog("Restaurar Item", "Você tem certeza que deseja restaurar este item?");
			}
		}

		protected void lnkRestore_Click(object sender, EventArgs e)
		{
			Licensing license = _licenseTable.Find(l => l.Id.Value == int.Parse(((LinkButton)sender).CommandArgument));
		}

		protected void gvHistory_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				RadioButton rd = ((RadioButton)e.Row.Cells[8].FindControl("rdRestore"));
				rd.Attributes.Add("LicenseId", e.Row.Cells[0].Text);
			}
		}

		void ShowMessageDialog(string title, string message)
		{
			WebLicenseGenerator.UC.Messaging messaging = ((WebLicenseGenerator.UC.Messaging)this.Master.FindControl("errorMessaging"));
			messaging.Message = message;
			messaging.Title = title;
			messaging.ShowMessageDialog();
		}

		void ShowConfirmationDialog(string title, string message)
		{
			_confirmation.Message = message;
			_confirmation.Title = title;
			_confirmation.ShowConfirmationDialog();
		}

		void OnConfirmation(object sender, ConfirmationEventArgs e)
		{
			if (e.Result == ConfirmationResult.Yes)
			{
				_licenseBusiness = new Licenca();
				_licenseBusiness.Restaurar(_selectedLicense);

				btSearch_Click(this.btSearch, new EventArgs());

				this.ShowMessageDialog("Restauração completa", "Restauração realizada com sucesso.");
			}
		}

		void LoadAliases()
		{
			_aliasBusiness = new Sinacor.Infra.Core.Licensing.Business.Alias();

			cbAliases.DataSource = _aliasBusiness.Selecionar(new Sinacor.Infra.Core.Licensing.Alias());
			cbAliases.DataTextField = "Nome";
			cbAliases.DataValueField = "ID";
			cbAliases.DataBind();
			cbAliases.Items.Insert(0, "");
		}

		bool ValidatePageFields()
		{
			return (dpHistoryDate.IsValid && txtLicenseId.IsValid);
		}
	}
}